<!--
 * @Author: jhw jiaxianshengye@gmail.com
 * @LastEditTime: 2025-07-31 16:37:54
 * @LastEditors: jhw
 * @Description: 文件描述
-->
<template>
  <div ref="container" class="lazy-chart">
    {{ num }}
    <div v-if="!isLoaded" class="chart-skeleton"></div>
    <div v-if="isLoaded" ref="chartEl" class="chart"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import echarts from '@/plugins/index'
const props = defineProps({
  options: {
    default: {},
  },
  type: {},
  num: {},
})

const container = ref(null)
const chartEl = ref(null)
const isLoaded = ref(false)
let chartInstance: any
let observer: any

const initChart = () => {
  nextTick(() => {
    if (!chartEl.value) return

    chartInstance = echarts.init(chartEl.value)
    chartInstance.setOption(props.options)

    // 添加resize监听
    const resizeHandler = () => chartInstance.resize()
    window.addEventListener('resize', resizeHandler, { passive: true })

    isLoaded.value = true

    // 清理函数
    return () => {
      window.removeEventListener('resize', resizeHandler)
      chartInstance.dispose()
    }
  })
}

onMounted(() => {
  observer = new IntersectionObserver(
    ([entry]) => {
      if (entry.isIntersecting) {
        console.log(`Chart ${props.num} entered viewport`)

        // 先设置 isLoaded=true 让 DOM 渲染
        isLoaded.value = true

        // 延迟初始化图表
        setTimeout(() => {
          // initChart()
          // observer?.disconnect()
          requestAnimationFrame(() => {
            initChart()
            observer?.disconnect()
          })
        }, 0) // 给 DOM 渲染留出时间
      }
    },
    {
      threshold: 0.01,
      rootMargin: '0px 0px 100px 0px', // 提前100px加载
    },
  )

  if (container.value) {
    observer.observe(container.value)
  }
})

onUnmounted(() => {
  observer?.disconnect()
  chartInstance?.dispose()
})
</script>
<style>
.lazy-chart {
  width: 100%; /* 更灵活的宽度 */
  height: 400px; /* 更合理的高度 */
  border: 1px solid black;
  margin-bottom: 20px;
}
.chart {
  height: 400px; /* 必须设置固定高度 */
}
</style>
